const nrfDfu = uni.requireNativePlugin('UUCoder-nRF-DFU');
import * as utils from '@/utils/utils.js';
import store from '@/store/index.js'
let saveFilePath = '';

// 获取 头环 版本 
function getDeviceVersion() {
	console.log('get device version...');
	let buffer = new ArrayBuffer(7);
	let dataView = new DataView(buffer);
	dataView.setUint8(0, 0x68);
	dataView.setUint8(1, 0x00);
	dataView.setUint8(2, 0x07);
	dataView.setUint8(3, 0x10);
	dataView.setUint8(4, 0x47);
	dataView.setUint8(5, 0x3a);
	dataView.setUint8(6, 0x16);
	getApp().writeBLECharacteristicValue(buffer);
}

function downloadFile() {
	// Download();
	uni.downloadFile({
		url: 'https://xch.jseihc.com/public/platform/headband_dfu_packet/EI-B100_DFU.zip',
		success(res) {
			console.log('download success!', res);
			if (res.statusCode === 200) {
				// 将临时文件 保存到本地
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success(result) {
						console.log(result);
						saveFilePath = result.savedFilePath;
						startDFU(result.savedFilePath);
					},
					fail(err) {
						console.log(err);
					}
				});
			}
		}
	});
}

function Download() {
	var url = "https://xch.jseihc.com/public/platform/headband_dfu_packet/EI-B100_DFU.zip"
	let dtask = plus.downloader.createDownload(url, {
			//本地路径开头使用file://，跟上手机文件本地目录storage/emulated/0，就是用户文件管理器能看到的了，之后我创建微垠作为文件夹，后缀是用于文件命名和格式修改，大家可以使用变量。
			filename: "file://storage/emulated/0/AnnoyFreeDFU/" //利用保存路径，实现下载文件的重命名
		},
		function(d, status) {
			console.log('klfakjfk',d);
			//d为下载的文件对象
			if (status == 200) {
				//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
				let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
				// plus.runtime.openFile(d.filename); //选择软件打开文件
			} else {
				//下载失败
				plus.downloader.clear(); //清除下载任务
			}
		})
	dtask.start();
}

function _showLoading(str){
	uni.showLoading({
		title: str
	});
}

function startDFU(filePath) {
	let that = this;
	let showLoading = plus.nativeUI.showWaiting('等待升级...',{
		width: '40%',
		height: '100px'
	})
	
	// let dfuFile = '/storage/emulated/0/Android/data/com.jseihc.AnnoyFree/apps/__UNI__B403FD7/doc/uniapp_save/16504269191230.zip'
	let dfuFile = '/storage/emulated/0/Android/data/com.jseihc.AnnoyFree/apps/__UNI__B403FD7/' + filePath.substring(1);
	const res = nrfDfu.dfu(getApp().globalData.deviceId, dfuFile, event => {
		if (event && event.method) {
			console.log('event<>>', event);
			switch (event.method) {
				case 'onDeviceConnecting':
					console.log('onDeviceConnecting: ', res.data);
					break;
				case 'onDeviceConnected':
					console.log('onDeviceConnected: ', res.data);
					break;
				case 'onDeviceDisconnecting':
					console.log('onDeviceDisconnecting: ', res.data);
					break;
				case 'onDeviceDisconnected':
					console.log('onDeviceDisconnected: ', res.data);
					break;
				case 'onDfuProcessStarting':
					console.log('onDfuProcessStarting: ', res.data);
					// _showLoading('等待升级...')
					showLoading.setTitle('等待升级...')
					// 此处提示 进入bootloader模式
					store.commit('isDFU', true);
					break;
				case 'onDfuProcessStarted':
					console.log('onDfuProcessStarted: ', res.data);
					break;
				case 'onProgressChanged':
					showLoading.setTitle(`进度: ${event.data.percent}% `)
					break;
				case 'Changed':
					console.log('Changed: ', res.data);
					break;
				case 'onDfuCompleted':
					console.log('DFU 成功!: ', res.data);
					showLoading.close()
					// uni.hideLoading()
					uni.showToast({
						title: '升级成功!',
						icon: 'success'
					})
					store.commit('isDFU', false);
					// 尝试重新连接
					let obj = {
						deviceId: store.state.bleId
					};
					getApp().openBluetoothAdapter1(obj);
					removeFile();
					break;
				case 'onDfuAborted':
					console.log('onDfuAborted: ', res.data);
					break;
				case '':
					console.log(': ', res.data);
					break;
			}
		}
	});
	if (!res) {
		console.error('DFU执行失败');
	}
}

function removeFile() {
	uni.removeSavedFile({
		filePath: saveFilePath,
		success(res) {
			console.log('remove success', res);
		}
	})
}

module.exports = {
	getDeviceVersion,
	downloadFile
}
